﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace WayCloud.Utility
{
    public class CustomModelBinder : DefaultModelBinder
    {
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Dictionary<string, bool> startedValid = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

            //获取模型的验证结果
            var results = ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(bindingContext.Model);

            foreach (ModelValidationResult validationResult in results)
            {
                string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);

                //if(bindingContext.PropertyFilter(subPropertyName)) {

                //bindingContext.PropertyFilter 是一个 delegate, 
                //如果指定的 member 在 BindAttribute 的 Include 的列表内
                //（或者非 Exclude 的列表内），返回 true, 否则为 false

                //部分验证的功能就是通过它的结果来实现的
                if (!bindingContext.PropertyFilter(validationResult.MemberName)) continue;
                if (!startedValid.ContainsKey(subPropertyName))
                {
                    startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
                }
                if (startedValid[subPropertyName])
                {
                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
                }
            }
        }

    }
}